package com.sale.succ.forms;

import java.util.Properties;

import com.sale.succ.components.DefForm;
import com.sale.succ.components.DefInput;
import com.sale.succ.components.DefLabel;
import com.sale.succ.system.TradeMarketException;
import com.sale.succ.utils.SystemConstants;
import com.sale.succ.utils.TraderConstants;
import com.sale.succ.utils.TraderHelper;

import eve.fx.Insets;
import eve.fx.gui.WindowConstants;
import eve.sys.Event;
import eve.sys.EventListener;
import eve.ui.CellPanel;
import eve.ui.Label;
import eve.ui.event.ControlEvent;

public class SystemPropsForm extends DefForm {
	public SystemPropsForm() {
		title = TraderHelper.getLabel(TraderConstants.SYSTEM_PROPS_LABEL);
		initData();
		addLast(getMainPanel());
		
		
		doButtons(OKB | CANCELB);
		ok.addListener(new EventListener() {
			public void onEvent(Event ev) {
				if (ev.type == ControlEvent.PRESSED) {
					save();
					exit(0);
				}
			}

		});
		windowFlagsToSet |= WindowConstants.FLAG_MAXIMIZE;
	}

	private CellPanel mainPanel;

	protected CellPanel getMainPanel() {
		if (mainPanel == null) {
			mainPanel = new CellPanel();
			mainPanel.defaultTags.set(TAG_INSETS, new Insets(5, 5, 5, 5));

			DefLabel helloLabel = new DefLabel(TraderHelper
					.getLabel(TraderConstants.SYSTEM_PROPS_LABEL));

			mainPanel.addLast(helloLabel).setControl(HCENTER).setCell(HGROW);

			Label ftpLabel = new Label(TraderHelper
					.getLabel(TraderConstants.FTP_SERVER_LABEL));
			mainPanel.addNext(ftpLabel).setCell(HGROW);
			mainPanel.addNext(getFtpInput()).setCell(HGROW);

		}
		return mainPanel;
	}

	Properties currentProperties;

	private void initData() {
		currentProperties = TraderHelper.getSystemProps();
		if(currentProperties.getProperty(SystemConstants.FTP_SERVER_IP) != null){
			getFtpInput().text = currentProperties.getProperty(SystemConstants.FTP_SERVER_IP);
		}
	}

	private DefInput ftpInput;

	public DefInput getFtpInput() {
		if (ftpInput == null) {
			ftpInput = new DefInput();
			ftpInput.columns = 12;
		}
		return ftpInput;
	}

	private void save() {
		try {
			currentProperties.put(SystemConstants.FTP_SERVER_IP, getFtpInput().text);
			TraderHelper.saveSystemProps(currentProperties);
		} catch (Exception ex) {
			new TradeMarketException(ex.getMessage(), TraderHelper.getLabel(TraderConstants.PROCESS_ABORTED));
		}

	}

	public boolean canExit(int exitCode) {
		if (exitCode == 1)
			return false;
		return super.canExit(exitCode);
	}

}
